package application;


import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.text.TextUtils;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.io.ReadProperties;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;
import com.rey.material.app.ThemeManager;
import com.socks.library.KLog;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Set;

import app.Login;
import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import menhoo.com.i8officelibrary.R;
import model.EmployeeResultDB;
import model.LoginUser;
import tools.ToastUtil;

/**
 * Created by yanglei on 15/9/22.
 */
public class AppApplication extends UIApplication {


    private static LoginUser User;
    private static String ALiYunDeviceId = null;
    private static String signalrID = null;
    private static ReadProperties readProperties = null;
    private static Class loginClass = Login.class;
    private static IWXAPI weixinApi;
    private static AppApplication app;
    private int notifyNum = 1;
    /*
    是否在每次进入主页面时，弹出更新提示信息
     */
    public static boolean isMainUpdateInfo = true;

    @Override
    public void DBUpdate(DbUtils db, int oldVersion, int newVersion) {
        super.DBUpdate(db, oldVersion, newVersion);
        try {
            db.deleteAll(EmployeeResultDB.class);
            LogUtils.e("xxxx删除成功");
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    public int getNotifyNum() {
        return notifyNum++;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
    }

    public void setNotification() {
        SharedPreferences sp = AppApplication.getInstance().getSharedPreferences("sp", Context.MODE_PRIVATE);
        boolean isShow = sp.getBoolean(UIKeyValueSet.IsNotificationOpen, true);
        if (isShow) {
            JPushInterface.setDebugMode(true);
            JPushInterface.init(this);
            BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(this);
            builder.notificationFlags = Notification.FLAG_AUTO_CANCEL
                    | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
//        builder.notificationDefaults =
//                Notification.DEFAULT_SOUND
//                | Notification.DEFAULT_VIBRATE
//                | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
            JPushInterface.setPushNotificationBuilder(0, builder);
            if (JPushInterface.isPushStopped(this))
                JPushInterface.resumePush(this);

        } else {
            if (!JPushInterface.isPushStopped(this))
                JPushInterface.stopPush(this);
        }
    }

    public void resumePush() {
        if (JPushInterface.isPushStopped(this))
            JPushInterface.resumePush(this);
    }

    public void stopPush() {
        if (!JPushInterface.isPushStopped(this))
            JPushInterface.stopPush(this);
    }

    @Override
    public void init() {
        //设置 生产版本或者调试版本
        setUIApplicationType(UIApplicationType.Developer);
        //
        setRunDownloadService(true);
        setIsNetworkStateReceiver(true);
        ThemeManager.init(this, 2, 0, null);
        //
        getAppKeyValueSet().setInitKey(KeyConstant.Network2G3GTipCount, "false");
        getAppKeyValueSet().setInitKey(KeyConstant.IsDownloadUpdateTestApk, "false");
        //
//        initCloudChannel(this);//阿里推送
        initWeiXin(this);
        //从raw config.txt 中读取配置数据
        try {
            readProperties = new ReadProperties(this, R.raw.config);
            //仅第一次有效
            getAppKeyValueSet().setInitKey(KeyConstant.AppIPUrl, readProperties.getValue(KeyConstant.AppIPUrl));
            getAppKeyValueSet().setInitKey(KeyConstant.AppIconTitle, "app_icon_title.png");
            getAppKeyValueSet().setInitKey(KeyConstant.AppIconBackground, "app_icon_background.png");
            //每次都有效
            getAppKeyValueSet().writeAppSetPreferences(KeyConstant.AppUniquenessName, readProperties.getValue(KeyConstant
                    .AppUniquenessName));
            getAppKeyValueSet().writeAppSetPreferences(KeyConstant.AppDesc, readProperties.getValue(KeyConstant.AppDesc));
            //设置网站默认地址
            HttpUrlConstant.setWebSite(AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppIPUrl));
        } catch (Exception e) {
            LogUtils.e("" + e);
        }

    }

    @Override
    public void debug() {
        //HttpUrlConstant.setWebSite("oa.menhoo.com");//已在登陆页面实行自定义ip

    }

    @Override
    public void prduct() {
        //HttpUrlConstant.setWebSite("");//已在登陆页面实行自定义ip
        LogUtils.allowD = false;
        LogUtils.allowE = false;
        LogUtils.allowI = false;
        LogUtils.allowV = false;
        LogUtils.allowW = false;
        LogUtils.allowWtf = false;
    }

    public static void openLogin(Context context) {
        if (loginClass != null) {
            context.startActivity(new Intent(context, loginClass));
        }

    }

    public static void setLoginClass(Class loginClass1) {
        loginClass = loginClass1;
    }

    public static LoginUser getUser() {
        //从数据库中读取
        try {
            LoginUser user = getDB().findFirst(LoginUser.class);
            if (user != null) {
                User = user;
            }
        } catch (Exception e) {
            User = null;
        }
        return User;
    }

    public static AppApplication getInstance() {
        return app;
    }

    public static void setUser(LoginUser user) {
        User = user;
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    KLog.e(logs + ":" + alias);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    //別名設置成功之後恢復推送
                    SharedPreferences sp = AppApplication.getInstance().getSharedPreferences("sp", Context.MODE_PRIVATE);
                    boolean isShow = sp.getBoolean(UIKeyValueSet.IsNotificationOpen, true);
                    if (isShow && !TextUtils.isEmpty(alias)) {
                        resumePush();
                    }
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    KLog.e(logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 10);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    KLog.e(logs);
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    KLog.e("Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    KLog.e("Unhandled msg - " + msg.what);
            }
        }
    };

    public static void setSignalrID(String connid) {
        signalrID = connid;
    }

    public static String getSignalrID() {
        if (TextUtils.isEmpty(signalrID)) {
            return "";
        }
        return signalrID;
    }

    /**
     * 初始化云推送通道
     * 移动推送Android SDK错误码说明
     * 错误名称	错误码（Error Code）	错误描述和解决办法（Error Message）
     * NO_NETWORK	1101	网络不可用
     * REG_FAIL	1056	注册/鉴权失败(请检查AppSecret配置)
     * INVAILD_APPKEY	1052	AppKey不存在
     * INVAILD_PACKAGENAME	1053	包名与配置的不符
     * INVAILD_APPSECRET	1054	Appsecret不合法
     * NETWORK_UNSTABLE	1105	网络不稳定或连接异常
     * INVAILD_SERVER_RETRUN	1115	不合法的服务端返回（请检查返回是否被篡改）
     * SYSTEM_UNKNOWN_ERROR	1108	系统未知异常
     *
     * @param applicationContext
     */
    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                LogUtils.d("init cloudchannel success");
                PushServiceFactory.getCloudPushService().setNotificationSmallIcon(R.mipmap.icon_small58);
                ALiYunDeviceId = PushServiceFactory.getCloudPushService().getDeviceId();

//                String id =PushServiceFactory.getCloudPushService().getDeviceId();
//                LogUtils.e("xxx:"+id);
//                MessageUtil.showShortToast(getApplicationContext(), "" + id);

            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                if (errorCode == "1101") {
                    MessageUtil.showShortToast(getApplicationContext(), "推送:网络不可用");
                } else if (errorCode == "1056") {
                    MessageUtil.showShortToast(getApplicationContext(), "推送:注册/鉴权失败(请检查AppSecret配置)");
                } else if (errorCode == "1052") {
                    MessageUtil.showShortToast(getApplicationContext(), "推送:AppKey不存在");
                } else if (errorCode == "1053") {
                    MessageUtil.showShortToast(getApplicationContext(), "推送:包名与配置的不符");
                } else if (errorCode == "1054") {
                    MessageUtil.showShortToast(getApplicationContext(), "推送:Appsecret不合法");
                } else if (errorCode == "1105") {
                    MessageUtil.showShortToast(getApplicationContext(), "推送:网络不稳定或连接异常");
                } else if (errorCode == "1115") {
                    MessageUtil.showShortToast(getApplicationContext(), "推送:不合法的服务端返回（请检查返回是否被篡改）");
                } else if (errorCode == "1108") {
                    MessageUtil.showShortToast(getApplicationContext(), "推送:推送--系统未知异常");
                }

                LogUtils.e("init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }

    private void initWeiXin(Context applicationContext) {

        ApplicationInfo appInfo = null;
        try {
            appInfo = applicationContext.getPackageManager()
                    .getApplicationInfo(getPackageName(),
                            PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String id = appInfo.metaData.getString("weixin.appid");
        if (id != null && !id.equalsIgnoreCase("")) {
            weixinApi = WXAPIFactory.createWXAPI(applicationContext, id, true);
            weixinApi.registerApp(id);
        } else {
            LogUtils.e("请设置 微信appid");
        }
    }

    public static IWXAPI getWeiXinApi() {
        return weixinApi;
    }

    public static String getALiYunDeviceId() {
        return ALiYunDeviceId;
    }

    public void setAlias(String alias) {
        if (alias == null) {
            return;
        }
        SharedPreferences sp = AppApplication.getInstance().getSharedPreferences("sp", Context.MODE_PRIVATE);
        String olderAlias = sp.getString("alias", "");
        KLog.e("olderAlias=="+olderAlias+"alias=="+alias);
        if (!olderAlias.equals(alias)) {
            sp.edit().putString("alias", alias).commit();
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
        }
    }

    public void clearAlias() {
        setAlias("");
    }
}
